package info.johnwheeler.gaestorage.servlet;

import info.johnwheeler.gaestorage.core.GSUtils;
import info.johnwheeler.gaestorage.core.Photo;
import info.johnwheeler.gaestorage.core.PhotoDao;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GStorageUploadServlet extends AbstractUploadServlet {
    private PhotoDao dao = new PhotoDao();

    @Override
    protected void showForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String acl = "public-read";
        String secret = getServletConfig().getInitParameter("secret");
        String accessKey = getServletConfig().getInitParameter("accessKey");
        String endpoint = getServletConfig().getInitParameter("endpoint");
        String successActionRedirect = getBaseUrl(req) + "gstorage?action=display&id=";
        String key = UUID.randomUUID().toString();
        String policy = GSUtils.createPolicyDocument(acl);
        String signature = GSUtils.signPolicyDocument(policy, secret);

        req.setAttribute("uploadUrl", endpoint);
        req.setAttribute("acl", acl);
        req.setAttribute("GoogleAccessId", accessKey);
        req.setAttribute("key", key);
        req.setAttribute("policy", policy);
        req.setAttribute("signature", signature);
        req.setAttribute("successActionRedirect", successActionRedirect);

        req.getRequestDispatcher("gstorage.jsp").forward(req, resp);
    }

    @Override
    protected void handleSubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String endpoint = getServletConfig().getInitParameter("endpoint");
        String title = req.getParameter("title");
        String caption = req.getParameter("caption");
        String key = req.getParameter("key");

        Photo photo = new Photo(title, caption);
        photo.setPhotoPath(endpoint + key);
        dao.save(photo);

        PrintWriter out = resp.getWriter();
        out.println(Long.toString(photo.getId()));
        out.close();
    }

    @Override
    protected void showRecord(long id, HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        Photo photo = dao.findById(id);
        String photoPath = photo.getPhotoPath();
        resp.sendRedirect(photoPath);
    }

    private static String getBaseUrl(HttpServletRequest req) {
        String base = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/";
        return base;
    }

}
